<!DOCTYPE html>
<html>

<head>
    <title>分配客户阶段</title>
    <link rel="stylesheet" href="/cusmanage/css/layui.css">
    <link rel="stylesheet" href="/cusmanage/css/dragslot.css">
    <link rel="stylesheet" href="/cusmanage/css/common.css">
    <link rel="stylesheet" href="/cusmanage/css/manager.css">
</head>

<body>
    <!-- 未设置客户 设置 -->
    <div id="lmheaderSet" style="">
        <!-- 1 -->
        <div class="layui-form" action="" style="margin: 10px 0 0 10px;">
          <div class="layui-inline">
            <div class="layui-input-inline">
              <input type="text" name="title" placeholder="请输入名称" id="search_input" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline">
              <button type="submit" class="layui-btn layui-btn-normal search_button">搜索</button> 
            </div>
          </div>
        </div>
        <div class="client-step1">
            <!--     <form class="layui-form" id="search" action="" style="margin: 17px 0;">
        <input type="hidden" name="searchTag" id="searchTag">
        <div class="layui-inline" style="position: relative;z-index: 1;">
          <label class="layui-form-label">客户标签</label>
          <div class="layui-input-inline" style="width: 200px;">
            <div class="tags-filter">
              <div class="tags-filter-content">
                <span class="placeholder">请选择标签</span> -->
            <!-- <span class="layui-badge-rim filter-tag">核心 <i class="layui-icon layui-icon-close"></i></span> -->
            <!--  </div>
              <i class="layui-icon layui-icon-down" style="color: #ccc;"></i>
            </div>
          </div>
        </div>
        <div class="layui-inline">
          <label class="layui-form-label">搜索客户</label>
          <div class="layui-input-inline">
            <input type="text" name="name" value="" autocomplete="off" placeholder="请输入要搜索客户" class="layui-input" style="display: inline-block;width: 200px;padding-right: 25px;">
            <i class="layui-icon layui-icon-search" onclick="search()" style="display: inline-block;margin-left: -26px;color: #888;"></i>
          </div>
        </div>
      </form> -->
            <div class="lm-panel-table mcheckbox-table">
                <table class="layui-hide" id="testTable" lay-filter="testTable"></table>
                <!-- <table class="layui-table lm-table" lay-data="!{id:'testTable',height:500, page:!{limit:10}}" lay-filter="panelTable" lay-skin="line">
          <thead>
            <tr>
              <th lay-data="!{checkbox:true,field:'id'}"></th>
              <th lay-data="!{field:'name', width: 220}">未设置客户</th>
              <th lay-data="!{field:'username', width: 200}">所属员工</th>
              <th lay-data="!{field:'tag', width: 230}">标签</th>
              <th lay-data="!{field:'createtime', width: 200}">添加时间</th>
            </tr> 
          </thead> -->
                <!--  <tbody>
            {loop $noset_externalcontact_list as $noset_et}
            <tr>
              <td class="panel-table-value">!{"avatar":"{$noset_et->avatar}","id":"{$noset_et->id}","name":"{$noset_et->name}"}</td>
              <td>
                <div class="flex lm-table-user">
                  <img src="{$noset_et->avatar}" alt="">
                  <div class="flex-1">
                    <p>{$noset_et->name}</p>
                    <p style="color: #5ec75d;">@微信</p>
                  </div>
                </div>
              </td>
              <td>
                <div class="service-card">
                  <i class="layui-icon layui-icon-friends"></i>{$h->get_user_by_id($noset_et->wid,$noset_et->user_id)['name']}
                </div>
              </td>
              <td>
                {loop $noset_et->et_tags as $et_tag}
                <span class="layui-badge-rim lm-table-tag">{$tagArr[$et_tag]}</span>
                {/loop}
              </td>
              <td>{date("Y-m-d H:i:s",$noset_et->createtime)}</td>
            </tr>
            {/loop}
          </tbody> -->
                <!-- </table> -->
            </div>
            <div style="text-align: right;padding: 10px 40px 20px;">
                <button onclick="parent.layer.closeAll()" class="layui-btn layui-btn-primary">取消</button>
                <button class="layui-btn layui-btn-normal set-client-status">设置客户状态</button>
            </div>
        </div>
        <!-- 2 -->
        <div class="client-step2" style="display: none;">
            <form class="layui-form" id="form2" action="" style="margin: 17px 0;">
                <input type="hidden" name="external_id" id="et_id" value="">
                <div class="layui-inline">
                    <label class="layui-form-label" style="width: auto;">选择客户状态</label>
                    <div class="layui-input-inline">
                        <select name="clientStatus" id="clientStatus">
                            <option value="0"></option>
                            {loop $level_manager as $manager}
                            <option value="{$manager->sequence}">{$manager->name}</option>
                            {/loop}
                        </select>
                    </div>
                </div>
            </form>
            <div style="padding: 0 17px 20px;font-size: 13px;color: #666;min-height: 200px;">
                <p style="margin-bottom: 15px;">已选择<span class="set-client-num">1</span>个客户</p>
                <div class="flex client-step2-users">
                </div>
            </div>
            <div style="text-align: right;padding: 10px 40px 20px;">
                <button class="layui-btn layui-btn-primary set-client-prev">上一步</button>
                <button class="layui-btn layui-btn-normal set-client-confirm" lay-submit lay-filter="updLevelManagers">完成</button>
            </div>
        </div>
    </div>
    <!-- 选择客户企业标签 -->
    <div id="tagsPanel" style="display: none;padding: 20px;">
        {loop $eTags as $eTag}
        <p class="tags-panel-title">{$eTag->group_name}</p>
        <div class="flex tags-panel-wrap">
            {loop $eTag->etags as $etag}
            <span class="tags-panel-item" data-etagid="{$etag['id']}">{$etag['name']}</span>
            {/loop}
        </div>
        {/loop}
        <div style="text-align: center;margin: 20px auto 10px;">
            <button class="layui-btn layui-btn-primary layui-btn-sm tags-panel-clear" style="width: 80px;">清空</button>
            <button class="layui-btn layui-btn-normal layui-btn-sm tags-panel-confirm" style="width: 80px;">确定</button>
        </div>
    </div>
</body>
<script src="/js/jquery.min.js"></script>
<script src="/cusmanage/js/layui.all.js"></script>
<script src="/cusmanage/js/common.js"></script>
<script src="/js/ajax.js"></script>
<script type="text/javascript">
function search() {
    var searchData = $('#search').serialize();
    console.log(searchData);
}
</script>
<script>
// layui.use('form', function(){
//   var form = layui.form;
//   // 监听提交  
//   form.on('submit(updLevelManager)',function(data){
//     var form3 = $('#form3').serialize();
//     myAjaxPost(false, true, 'update_level_manager.html', form3, function (resp) {
//       // console.log(resp);
//       if(resp.status == 'success') {
//         layer.msg(resp.msg);
//           setTimeout(function(){
//             window.location.reload();
//           },1000);
//           // layer.close(index);
//       }else{
//         alert(resp.msg);
//       }
//     });
//     return false;
//   })
// })

// table中客户阶段调整
layui.use('form', function() {
    var form = layui.form;

    form.on('select(lmtlevel)', function(data) {
        var select_lmtlevel = $("#select_lmtlevel");
        // console.log(select_lmtlevel);
        let old_sequence = select_lmtlevel.data('sequence');
        let id = select_lmtlevel.data('id');
        let val = data.value;
        // console.log(old_sequence, id,val);

        if (val != old_sequence) {
            myAjaxPost(false, true, 'update_level_manager.html', !{ clientStatus: val, external_id: id }, function(resp) {
                if (resp.status == 'success') {
                    layer.msg(resp.msg);

                } else {
                    alert(resp.msg);
                }
            })
        }
    })
});

// 筛选客户标签
$('.tags-filter').on('click', function(e) {
    if (e.target.classList.contains('layui-icon-close')) { // 删除
        var $item = $(e.target).parent()
        var value = $item.text()
        $item.remove()
        var $panelTags = $('.tags-panel-item.on');
        var tag_arr = $("#searchTag").val();
        tag_arrs = tag_arr.split(',');
        for (var i = 0, l = $panelTags.length; i < l; i++) {
            if ($panelTags[i].innerText === value) {
                $($panelTags[i]).removeClass('on');
                tag_arrs.splice($.inArray($panelTags[i].dataset.etagid, tag_arrs), 1);
            }
        }
        $("#searchTag").val(tag_arrs);
        if (!$('.filter-tag').length) {
            $('.tags-filter-content').html('<span class="placeholder">请选择标签</span>')
        }
    } else { // 选择标签
        layer.open({
            title: ['企业标签', 'font-weight:bold;'],
            type: 1,
            shadeClose: false,
            content: $('#tagsPanel')
        })
    }
})
$(document).on('click', '.tags-panel-item', function() {
    if ($(this).hasClass('disabled')) return;
    $(this).toggleClass('on');

})
// 清空
$('.tags-panel-clear').on('click', function() {
    $('.tags-panel-item').removeClass('on')
    $('.tags-filter-content').html('<span class="placeholder">请选择标签</span>')
    $("#searchTag").val('');
    layer.close(layer.index)
})
// 确定
$('.tags-panel-confirm').on('click', function() {
    // console.log('---')
    var $tags = $('.tags-panel-item.on');
    var html = '';
    var tag_arr = [];
    for (var i = 0, l = $tags.length; i < l; i++) {
        html += '<span class="layui-badge-rim filter-tag">' + $tags[i].innerText + '<i class="layui-icon layui-icon-close"></i></span>';
        tag_arr.push($($tags[i]).data('etagid'));
    }
    if (tag_arr) {
        $("#searchTag").val(tag_arr);
    }

    if (!html) {
        html += '<span class="placeholder">请选择标签</span>'
    }
    $('.tags-filter-content').html(html)
    layer.close(layer.index)
})

function getPageSelected() {
    var arr = layui.table.checkStatus('testTable').data
    var result = []
    for (var i = 0, l = arr.length; i < l; i++) {
        var item = arr[i]
        result.push({
            id: item.id,
            name: item.name,
            avatar: item.avatar
        })
    }
    return result
}
var currTablePage = 1,
    tableSelected = [] // 以页码为key，result为value
// var panelSelectedUsers = {}
// 弹窗-设置客户标签的table
// layui.use('table', function(){
//   var table = layui.table;

//   table.on('checkbox(panelTable)', function(obj){
//     console.log(obj.checked); //当前是否选中状态
//     console.log(obj.data); //选中行的相关数据
//     // console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one

//     if (obj.checked) {
//       // panelSelectedUsers[obj.data.用户id] = obj.data
//       panelSelectedUsers['1'] = obj.data
//     } else {
//       // delete panelSelectedUsers[obj.data.用户id]
//       delete panelSelectedUsers['1']
//     }
//   })
// })
// 弹窗-设置客户标签的table
layui.use('table', function() {
    var table = layui.table;
    table.render({
        id: "userTable",
        elem: '#testTable',
        url: 'get_noset_ex.html',
        parseData: function(res) { //res 即为原始返回的数据
            console.log(res);
            var data = res.data
            var thePageSelected = tableSelected[res.page]
            if (thePageSelected && thePageSelected.length) {
                $.each(data, function(index, item) {
                    if (thePageSelected.some(function(a) {
                            return a.id === data[index].id
                        })) {
                        data[index]['LAY_CHECKED'] = true
                    }
                })
            }
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": data //解析数据列表
            };
        },
        cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
            ,
        page: true,
        limits: [10, 20, 30],
        limit: 10,
        cols: [
                [
                    // !{type:'numbers'}
                    // !{type:'checkbox'}
                    // ,!{type: 'checkbox', field: 'id', templet: function(res) {
                    //     return '!{"avatar":' + res.avatar + ',"id":' + res.id + ',"name":' + res.name +'}'
                    //   }}
                    !{ checkbox: true, field: 'id' }, !{ field: 'name', width: "10%", title: '未设置客户' }, !{ field: 'user_id', width: "20%", title: '所属员工' }, !{ field: 'tags', title: '标签', width: '30%', minWidth: 100 } //minWidth：局部定义当前单元格的最小宽度，layui 2.2.1 新增
                    , !{ field: 'createtime', width: '40%', title: '添加时间', sort: true }
                ]
            ]
            // 页码变化会触发
            ,
        done: function(res, curr, count) {
            // console.log('当前页码: ' + curr)
            currTablePage = curr
            // $('.mcheckbox-table td .layui-form-checked').click() // 如需翻页清除选中项
        }
    });
    $('.search_button').click(function() {
        var inputVal = $("#search_input").val();
        table.reload('userTable', {
            url: 'get_noset_ex.html'
                // ,methods:"post"
                ,
            request: {
                pageName: 'page' //页码的参数名称，默认：page
                    ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            where: {
                name: inputVal
            },
            page: {
                curr: 1
            }
        });
    })
    //转换静态表格
    //   table.init('panelTable', {
    //     page: !{limit: 1},
    //     // 页码变化会触发
    //     done: function(res, curr, count) {
    //       console.log('当前页码: ' + curr)
    //       currTablePage = curr
    //       // $('.mcheckbox-table td .layui-form-checked').click() // 如需翻页清除选中项
    //     }
    //   })

    table.on('checkbox(testTable)', function(obj) {
        // console.log('check...', obj)
        var result = getPageSelected()
        tableSelected[currTablePage] = result
        // if (!result.length) delete tableSelected[currTablePage] // 如果当页没有选中值，需要删除key的话
    })
})
// 设置客户状态按钮
// $('.set-client-status').on('click', function() {
//   var ks = Object.keys(panelSelectedUsers)
//   if (!ks.length) {
//     layer.msg('请至少选择一个客户')
//     return
//   }
//   console.log(ks);
//   $('.client-step1').hide()
//   $('.client-step2').fadeIn()
// })
// 设置客户状态按钮
$('.set-client-status').on('click', function() {
    var result = getPageSelected()
    // console.log('result: ', result)
    // console.log('all selected: ', tableSelected)
    var id_res = tableSelected.reduce(function(a, b) { return a.concat(b) }, []);
    // if (!result.length) {
    //   layer.msg('请至少选择一个客户')
    //   return
    // }
    // $('.client-step1').hide()
    // $('.client-step2').fadeIn()

    // var html = ''
    // for (var j = 0, jl = result.length; j < jl; j++) {
    //   html += '<div class=set-client-user data-id=' + result[j].id + '>< img src=' + result[j].avatar + ' alt=><span>' + result[j].name + '</span></div>'
    // }
    // $('.client-step2-users').html(html)

    // var checkedNodes = $('.mcheckbox-table [name="layTableCheckbox"]')
    // var valueNodes = $('.mcheckbox-table .panel-table-value')
    // var result = [];
    // var page = $(".mcheckbox-table .layui-laypage-curr").text();
    // console.log('page...',page);
    // var pageSize = 10;
    // 第一个是全选框，扔掉
    // for (var i = 1, l = checkedNodes.length; i < l; i++) {
    //   if (checkedNodes[i].checked) {
    //     result.push(JSON.parse(valueNodes[i - 1].innerText))
    //   }
    // }
    //处理翻页
    // var currentValueNodes = valueNodes.slice((page - 1)*pageSize)
    // for (var i = 1 , l = checkedNodes.length; i < l; i++) {
    //   if(checkedNodes[i].checked){
    //     result.push(JSON.parse(currentValueNodes[i - 1].innerText))
    //   }
    // }

    // console.log('result: ', result)

    if (!id_res.length) {
        layer.msg('请至少选择一个客户');
        return;
    }
    $('.client-step1').hide();
    $('.client-step2').fadeIn();

    var html = '';
    var et_id = [];
    for (var j = 0, jl = id_res.length; j < jl; j++) {
        html += '<div class=set-client-user data-id=' + id_res[j].id + '><img src="' + id_res[j].avatar + '" alt=""><span>' + id_res[j].name + '</span></div>';
        et_id.push(id_res[j].id);
    }
    $('.client-step2-users').html(html);
    $("#et_id").val(et_id.toString());
})
// 上一步
$('.set-client-prev').on('click', function() {
    $('.client-step2-users').empty();
    $('.client-step2').hide()
    $('.client-step1').show()
})
// 完成
$('.set-client-confirm').on('click', function() {
    layui.use('form', function() {
        var form = layui.form;
        // 监听提交  
        form.on('submit(updLevelManagers)', function(data) {
            if ($("#clientStatus").val() == 0) {
                layer.msg("请选择客户阶段");
                return;
            }
            var form2 = $('#form2').serialize();
            myAjaxPost(false, true, 'update_level_manager.html', form2, function(resp) {
                // console.log(resp);
                if (resp.status == 'success') {
                    layer.msg(resp.msg);
                    setTimeout(function() {
                        parent.location.reload();
                    }, 1000);
                    // layer.close(index);
                } else {
                    alert(resp.msg);
                }
            });
            return false;
        })
    })
    // alert('confirm')
})
</script>
<script>
layui.use('table', function() {
    var table = layui.table;
    //方法级渲染
    table.render({
        elem: '#tablea',
        url: 'json/demo.json',
        cols: [
            [
                { field: 'id', title: 'ID', align: 'center', width: 150 }, { field: 'username', title: '公司名称', align: 'center', width: 100 }
            ]
        ],
        id: 'testReload',
        page: true,
        height: 600,
        request: {
            pageName: 'page' //页码的参数名称，默认：page
                ,
            limitName: 'pageSize' //每页数据量的参数名，默认：limit
                ,
            statusName: 'status' //数据状态的字段名称，默认：code
                ,
            statusCode: 200 //成功的状态码，默认：0
        }
    });

})
</script>

</html>